package com.xjscrm.server.service.wwtags.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.MicaLabelAddMsg;
import com.uzai.mobile.collect.api.dto.msg.MicaLabelPushMsg;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.entity.SyncTagJob;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.common.entity.WwTags;
import com.xjscrm.common.entity.WwTagsUserid;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.constant.Const;
import com.xjscrm.server.mapper.SyncTagJobMapper;
import com.xjscrm.server.mapper.WwDeviceMapper;
import com.xjscrm.server.mapper.WwTagsMapper;
import com.xjscrm.server.mapper.WwTagsUseridMapper;
import com.xjscrm.server.service.msg.MsgSendService;
import com.xjscrm.server.service.wwtags.WwTagsService;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 企业微信客户添加实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class WwTagsServiceImpl implements WwTagsService {
    @Autowired
    private WwTagsMapper wwTagsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MsgSendService msgSendService;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private SyncTagJobMapper syncTagJobMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private WwTagsUseridMapper wwTagsUseridMapper;


    /**
     * 同步企业标签
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void tagsGroupPush(MicaTransDto micaTransDto) {
        log.info("--监控系统日志--同步标签开始--micaTransDto={}", JSONObject.toJSONString(micaTransDto));

        if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
            log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
            return;
        }

        //查询该机器人的配置方案
        WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
        if (wwDevice == null) {
            return;
        }
        Device device = DeviceTools.transDevice(wwDevice);
        if (device == null) {
            return;
        }
        int now = 1;


        //限流判断(同一个企业60秒之内只能同步一次标签)
        String rateLimitKey = "tagsGroupPush-corpId=" + device.getCorpId();
        Object object = redisTemplate.opsForValue().get(rateLimitKey);
        if (object != null) {
            return;
        }

        try {

            redisTemplate.opsForValue().set(rateLimitKey,rateLimitKey, 100, TimeUnit.SECONDS);


            //临时查询该企业的所有企业标签（找到一个一个则删除一个，剩下的表示不是微信中，数据库中错误的）
            List<WwTags> wwTagsList_enter = wwTagsMapper.findEnterListByCorpId(device.getCorpId(), device.getMerId());
            if (wwTagsList_enter == null) {
                wwTagsList_enter = new ArrayList<>();
            }

            //临时查询该企业的所有标签（找到一个一个则删除一个，剩下的表示不是微信中，数据库中错误的）
            List<WwTags> wwTagsList_private = wwTagsMapper.findPrivateListByDeviceUniqueId(device.getCorpId(), device.getDeviceUniqueId());
            if (wwTagsList_private == null) {
                wwTagsList_private = new ArrayList<>();
            }

            MicaLabelPushMsg micaLabelPushMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaLabelPushMsg.class);
            if (micaLabelPushMsg != null) {
                List<MicaLabelPushMsg.MicaLabelGroupMsg> groupMsgs = micaLabelPushMsg.getGroupMsgs();
                if (groupMsgs != null && groupMsgs.size() > 0) {
                    for (MicaLabelPushMsg.MicaLabelGroupMsg micaLabelGroupMsg : groupMsgs) {
                        //企业标签(同一个企业下的标签只能存在一次)
                        if (Tools.getInteger(micaLabelGroupMsg.getType()).intValue() == 1) {
                            //删除该企微标签
                            wwTagsList_enter.removeIf(item -> Objects.equals(micaLabelGroupMsg.getId(), item.getTagId()));
                            ////先根据tagId查询，查询到则修改,如果等于空，则用标签名称去查询
                            WwTags wwTags_enter_parent = wwTagsMapper.queryEnterTagByTagIdStr(micaLabelGroupMsg.getId(), device.getMerId());
                            if(wwTags_enter_parent != null){
                                wwTags_enter_parent.setTagName(micaLabelGroupMsg.getName());
                                wwTags_enter_parent.setUpdateTime(now);
                                if(StringUtils.isNotBlank(wwTags_enter_parent.getTagId()) && StringUtils.isNotBlank(wwTags_enter_parent.getExternalId())){
                                    wwTags_enter_parent.setStatus(1);
                                }
                                wwTagsMapper.update(wwTags_enter_parent);
                            }else{//如果等于空，则用标签名称去查询
                                List<WwTags> wwTags_enter_parent_list = wwTagsMapper.queryGroupEnterTagByTagName(micaLabelGroupMsg.getName(), device.getMerId(), device.getCorpId());
                                if (wwTags_enter_parent_list == null || wwTags_enter_parent_list.size() == 0) { //未找到，则插入
                                    wwTags_enter_parent = new WwTags();
                                    wwTags_enter_parent.setId(IdWorker.getId());
                                    wwTags_enter_parent.setMerId(micaTransDto.getMerId());
                                    wwTags_enter_parent.setType(micaLabelGroupMsg.getType());
                                    wwTags_enter_parent.setTagId(micaLabelGroupMsg.getId());
                                    wwTags_enter_parent.setTagName(micaLabelGroupMsg.getName());
                                    wwTags_enter_parent.setPid(0L);
                                    wwTags_enter_parent.setStatus(0);  //无效
                                    wwTags_enter_parent.setCorpId(device.getCorpId());
                                    wwTags_enter_parent.setSysGroup(0);
                                    wwTags_enter_parent.setCreateTime(now);
                                    wwTags_enter_parent.setUpdateTime(now);
                                    //插入
                                    wwTagsMapper.insert(wwTags_enter_parent);
                                } else if(wwTags_enter_parent_list.size() == 1){//只找到一条，则修改
                                    wwTags_enter_parent = wwTags_enter_parent_list.get(0);
                                    wwTags_enter_parent.setTagId(micaLabelGroupMsg.getId());
                                    wwTags_enter_parent.setUpdateTime(now);

                                    if(StringUtils.isNotBlank(wwTags_enter_parent.getTagId()) && StringUtils.isNotBlank(wwTags_enter_parent.getExternalId())){
                                        wwTags_enter_parent.setStatus(1);
                                    }

                                    wwTagsMapper.update(wwTags_enter_parent);
                                }else{
                                    wwTags_enter_parent = wwTags_enter_parent_list.get(0);
                                }
                            }

                            //判断该标签组下的标签存不存在
                            List<MicaLabelPushMsg.MicaLabelItemMsg> itemMsgs = micaLabelGroupMsg.getItemMsgs();
                            if (itemMsgs != null && itemMsgs.size() > 0) {
                                for (MicaLabelPushMsg.MicaLabelItemMsg itemMsg : itemMsgs) {

                                    try {
                                        //删除该企微标签
                                        wwTagsList_enter.removeIf(item -> Objects.equals(itemMsg.getId(), item.getTagId()));
                                        //先根据tagId查询，查询到则修改,如果等于空，则用标签名称去查询
                                        WwTags wwTags_enter_son = wwTagsMapper.queryEnterTagByTagIdStr(itemMsg.getId(), device.getMerId());
                                        if(wwTags_enter_son != null){
                                            wwTags_enter_son.setTagName(itemMsg.getName());
                                            wwTags_enter_son.setUpdateTime(now);
                                            if(StringUtils.isNotBlank(wwTags_enter_son.getTagId()) && StringUtils.isNotBlank(wwTags_enter_son.getExternalId())){
                                                wwTags_enter_son.setStatus(1);
                                            }
                                            wwTagsMapper.update(wwTags_enter_son);
                                        }else {//如果等于空，则用标签名称去查询
                                            List<WwTags> wwTags_enter_son_list = wwTagsMapper.queryEnterTagByTagName(itemMsg.getName(), wwTags_enter_parent.getId(), device.getMerId(), device.getCorpId());
                                            if (wwTags_enter_son_list == null || wwTags_enter_son_list.size() == 0) { //未找到，则插入
                                                wwTags_enter_son = new WwTags();
                                                wwTags_enter_son.setId(IdWorker.getId());
                                                wwTags_enter_son.setMerId(micaTransDto.getMerId());
                                                wwTags_enter_son.setDeviceUniqueId(device.getDeviceUniqueId());
                                                wwTags_enter_son.setType(Tools.getInteger(micaLabelGroupMsg.getType()));
                                                wwTags_enter_son.setTagId(itemMsg.getId());
                                                wwTags_enter_son.setTagName(itemMsg.getName());
                                                wwTags_enter_son.setPid(wwTags_enter_parent.getId());
                                                wwTags_enter_son.setStatus(0);  //无效
                                                wwTags_enter_son.setCorpId(device.getCorpId());
                                                wwTags_enter_son.setSysGroup(0);
                                                wwTags_enter_son.setCreateTime(now);
                                                wwTags_enter_son.setUpdateTime(now);
                                                wwTagsMapper.insert(wwTags_enter_son);
                                            } else if(wwTags_enter_son_list.size() == 1){//只找到一条，则修改
                                                wwTags_enter_son = wwTags_enter_son_list.get(0);
                                                wwTags_enter_son.setTagId(itemMsg.getId());
                                                wwTags_enter_son.setUpdateTime(now);
                                                if(StringUtils.isNotBlank(wwTags_enter_son.getTagId()) && StringUtils.isNotBlank(wwTags_enter_son.getExternalId())){
                                                    wwTags_enter_son.setStatus(1);
                                                }
                                                wwTagsMapper.update(wwTags_enter_son);
                                            }
                                        }
                                    }catch (Exception e){
                                        log.error("同步标签失败，tagName={}, corpId={}", itemMsg.getName(), device.getCorpId());
                                    }
                                }
                            }
                        } else if (Tools.getInteger(micaLabelGroupMsg.getType()).intValue() == 2) { //个人标签
                            //判断该标签组下的标签存不存在
                            List<MicaLabelPushMsg.MicaLabelItemMsg> itemMsgs = micaLabelGroupMsg.getItemMsgs();
                            if (itemMsgs != null && itemMsgs.size() > 0) {
                                for (MicaLabelPushMsg.MicaLabelItemMsg itemMsg : itemMsgs) {
                                    //判断是否是维护会员userid的标签
                                    if(!Tools.getStr(itemMsg.getName()).startsWith(Const.para.TAG_USERID)) {
                                        //删除该机器人的个人标签
                                        wwTagsList_private.removeIf(item -> Objects.equals(itemMsg.getId(), item.getTagId()));
                                        //判断标签组存不存在，不存在则添加
                                        WwTags wwTags_private_son = wwTagsMapper.queryPrivateTagByTagNameAndDeviceUniqueId(device.getDeviceUniqueId(), itemMsg.getId());
                                        if (wwTags_private_son == null) {
                                            //先要判断是否有默认分组，如果没有则不插入
                                            WwTags wwTags_defaultGroup = wwTagsMapper.queryDefaultByDevice(device.getDeviceUniqueId());
                                            if (wwTags_defaultGroup != null) {
                                                wwTags_private_son = new WwTags();
                                                wwTags_private_son.setId(IdWorker.getId());
                                                wwTags_private_son.setMerId(micaTransDto.getMerId());
                                                wwTags_private_son.setDeviceUniqueId(device.getDeviceUniqueId());
                                                wwTags_private_son.setType(Tools.getInteger(micaLabelGroupMsg.getType()));
                                                wwTags_private_son.setTagId(itemMsg.getId());
                                                wwTags_private_son.setTagName(itemMsg.getName());
                                                wwTags_private_son.setPid(wwTags_defaultGroup.getId());
                                                wwTags_private_son.setStatus(1);  //有效
                                                wwTags_private_son.setCorpId(device.getCorpId());
                                                wwTags_private_son.setSysGroup(0);
                                                wwTags_private_son.setCreateTime(now);
                                                wwTags_private_son.setUpdateTime(now);
                                                wwTagsMapper.insert(wwTags_private_son);
                                            }
                                        } else {
                                            wwTags_private_son.setTagName(itemMsg.getName());
                                            wwTags_private_son.setUpdateTime(now);
                                            //wwTagsMapper.update(wwTags_private_son);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //剩下的表示数据库多余的,全部清除
//            for (WwTags wwTags_enter : wwTagsList_enter) {
//                wwTagsMapper.deleteById(wwTags_enter.getId());
//            }
//
//            for (WwTags wwTags_private : wwTagsList_private) {
//                wwTagsMapper.deleteById(wwTags_private.getId());
//            }

            //修改标签同步成功
            SyncTagJob syncGroupJob = syncTagJobMapper.selectByDeviceUniqueIdAndStatus(device.getDeviceUniqueId(), 1);
            if (syncGroupJob != null) {
                syncGroupJob.setStatus(2);
                syncGroupJob.setUpdateTime(now);
                syncTagJobMapper.updateByIdSelective(syncGroupJob);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }finally {
            redisTemplate.delete(rateLimitKey);
            log.info("--监控系统日志--同步标签结束--");
        }
    }

    /**
     * 修改标签成功回调
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void tagsModifyPush(MicaTransDto micaTransDto) {
        try {
            log.info("--监控系统日志--开始--");

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //查询该机器人的配置方案
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }
            int now = DateUtil.getTime();

            MicaLabelAddMsg micaLabelAddMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaLabelAddMsg.class);
            if (micaLabelAddMsg != null) {
                //判断是否是维护会员userid的标签
                if (!Tools.getStr(micaLabelAddMsg.getName()).startsWith(Const.para.TAG_USERID)) {
                    //标签主键id
                    Long id = micaLabelAddMsg.getTaskId();
                    //标签id
                    String tagId = micaLabelAddMsg.getId();
                    //标签名称
                    String name = micaLabelAddMsg.getName();
                    //查询标签
                    WwTags wwTags = wwTagsMapper.queryById(id);
                    if (wwTags != null) {
                        //更新该标签的状态信息
                        wwTags.setTagId(tagId);
                        wwTags.setStatus(1); //有效
                        wwTags.setUpdateTime(now);
                        wwTagsMapper.update(wwTags);
                    }
                } else { //是以userid_开头的标签
                    //标签主键id
                    Long id = micaLabelAddMsg.getTaskId();
                    //标签id
                    String tagId = micaLabelAddMsg.getId();
                    //标签名称
                    String name = micaLabelAddMsg.getName();
                    //查询标签
                    WwTagsUserid wwTagsUserid = wwTagsUseridMapper.queryById(id);
                    if (wwTagsUserid != null) {
                        //更新该标签的状态信息
                        wwTagsUserid.setTagId(tagId);
                        wwTagsUserid.setStatus(1); //有效
                        wwTagsUserid.setUpdateTime(now);
                        wwTagsUseridMapper.update(wwTagsUserid);
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }finally {
            log.info("--监控系统日志--结束--");
        }

    }
}
